<template>
  <view class="exam-list-container">
    <view class="search-bar">
      <input type="text" v-model="searchKey" placeholder="请输入月考标题搜索" />
      <button @click="searchExam">搜索</button>
    </view>
    
    <view class="exam-table">
      <view class="table-header">
        <view class="table-cell">标题</view>
        <view class="table-cell">创建时间</view>
        <view class="table-cell">状态</view>
        <view class="table-cell">操作</view>
		<view class="table-cell">推送</view>
      </view>
      
      <view class="table-body">
        <view class="table-row" v-for="(exam, index) in examList" :key="index">
          <view class="table-cell">{{ exam.title }}</view>
          <view class="table-cell">{{ formatDate(exam.createTime) }}</view>
          <view class="table-cell">{{ exam.visible === true ? '已启用' : '已禁用' }}</view>
          <view class="table-cell">
            <button class="status-btn" :class="{ 'active': exam.visible }" 
				@click="toggleStatus(exam.title, !exam.visible)">{{ exam.visible? '禁用' : '启用' }}</button>
          </view>
		  <view class="table-cell">
		    <button @click="clickPush(exam.title)" :disabled="!exam.visible">推送</button>
		  </view>
        </view>
      </view>
    </view>
    
    <view class="pagination">
      <button :disabled="currentPage === 1" @click="prevPage">上一页</button>
      <text>{{ currentPage }}/{{ totalPages }}</text>
      <button :disabled="currentPage === totalPages" @click="nextPage">下一页</button>
    </view>
  </view>
</template>

<script>
import request from '@/utils/request.js';

export default {
  data() {
    return {
      examList: [],
      searchKey: '',
      currentPage: 1,
      pageSize: 10,
      totalPages: 1
    }
  },
  onLoad() {
	  console.log("onLoad 被调用")
    this.getExamList();
  },
  created() {
  	console.log('组件：created')
  	// 初始化数据请求
  	this.getExamList()
  },
  activated(){
	  console.log("activated 被调用")
	this.getExamList()  
  },
  methods: {
    async getExamList() {
      try {
		  console.log("title=" + this.searchKey)
        const res = await request.get('/api/score/list', {
          params: {
            title: this.searchKey,
            currentPage: this.currentPage,
            pageSize: this.pageSize
          }
        });
        console.log("获取月考列表：" , res)
		this.examList = res.content || [];
		this.totalPages = res.page.totalPages;
        // if (res.code === 200) {
        //   this.examList = res.data.list || [];
        //   this.totalPages = Math.ceil(res.data.total / this.pageSize);
        // } else {
        //   uni.showToast({
        //     title: res.message || '获取月考列表失败',
        //     icon: 'none'
        //   });
        // }
      } catch (error) {
        console.error('获取月考列表错误:', error);
        uni.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
      }
    },
    
    formatDate(timestamp) {
      if (!timestamp) return '';
      const date = new Date(timestamp);
      return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
    },
    
    async toggleStatus(title, status) {
      try {
		// const st = status === true ? true : false
		// console.log("更新成绩状态：" + st)
        const res = await request.post('/api/score/status', {
		  title: title,
          visible: status
        });
        
        uni.showToast({
			title: status === true ? '已启用' : '已禁用',
            icon: 'success'
        });
        this.getExamList();
        // } else {
        //   uni.showToast({
        //     title: res.message || '操作失败',
        //     icon: 'none'
        //   });
        // }
      } catch (error) {
        console.error('更改状态错误:', error);
        uni.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
      }
    },
    
    searchExam() {
      this.currentPage = 1;
      this.getExamList();
    },
    
    prevPage() {
      if (this.currentPage > 1) {
        this.currentPage--;
        this.getExamList();
      }
    },
    
    nextPage() {
      if (this.currentPage < this.totalPages) {
        this.currentPage++;
        this.getExamList();
      }
    }
  }
}
</script>

<style>
.exam-list-container {
  padding: 15px;
}

.search-bar {
  display: flex;
  margin-bottom: 20px;
}

.search-bar input {
  flex: 1;
  padding: 8px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  margin-right: 10px;
}

.search-bar button {
  padding: 8px 16px;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
}

.exam-table {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
}

.table-header {
  display: flex;
  background-color: #f5f7fa;
  font-weight: bold;
}

.table-row {
  display: flex;
  border-top: 1px solid #ebeef5;
}

.table-row:nth-child(even) {
  background-color: #fafafa;
}

.table-cell {
  flex: 1;
  padding: 12px;
  text-align: center;
  word-break: break-all;
}

.status-btn {
  background-color: #67c23a; /* 初始为禁用状态颜色 */
  color: white;
  border: none;
  padding: 5px 10px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.status-btn.active {
  background-color: #f56c6c; /* 启用状态颜色 */
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
}

.pagination button {
  padding: 8px 16px;
  margin: 0 10px;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
}

.pagination button:disabled {
  background-color: #c0c4cc;
  cursor: not-allowed;
}
</style>